package com.iss.ljx.spring.security;

import com.iss.ljx.login.entity.LoginUserEntity;
import com.iss.ljx.mybatis.entity.PtUserEntity;
import com.iss.ljx.login.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 流星
 */
@Slf4j
@Service("userDetailsService")
public class GdmtUserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private LoginService loginService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        PtUserEntity ptUserEntity = loginService.queryUserInfoByUserName(username);
        if(ptUserEntity == null){
            throw new IllegalArgumentException(username + " user is not exit.");
        }


        List<String> roleList = loginService.queryRoleByID(ptUserEntity.getUserUuid());
        List<GrantedAuthority> collection = new ArrayList<>();
        for(String role:roleList){
            if(role != null && !"".equals(role)){
                collection.add(new SimpleGrantedAuthority("ROLE_" + role));
            }
        }

        // 参数分别是：用户名，密码，用户权限
        LoginUserEntity user = new LoginUserEntity(username, ptUserEntity.getPassword(), collection);
        user.setNiceName(ptUserEntity.getNiceName());
        user.setEmail(ptUserEntity.getEmail());
        user.setUserUuid(ptUserEntity.getUserUuid());
        user.setMobile(ptUserEntity.getMobile());

        return user;
    }

}
